package com.mesd.framework.dao.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.mesd.framework.dao.BaseDao;
import com.mesd.framework.util.DateUtil;

@Component("baseDao")
public class BaseDaoImpl implements BaseDao {
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private HibernateTemplate hibernateTemplate;
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	
	public Serializable saveObject(Object obj){
		return hibernateTemplate.save(obj);
	}
	
	public void saveOrUpdateObject(Object obj){
		hibernateTemplate.saveOrUpdate(obj);
		
	}
	
	public void saveOrUpdateAll(Collection objs){
		hibernateTemplate.saveOrUpdateAll(objs);
	}
	
	public void removeObject(Object obj){
		hibernateTemplate.delete(obj);
	}
	
	public void removeAll(Collection objs){
		hibernateTemplate.deleteAll(objs);
	}
	
	public void refreshObject(Object obj){
		hibernateTemplate.refresh(obj);
	}
	
	public List getObjects(Class clazz,String propertyName,Object value){
		Session session = getSession();
		Criteria criteria = session.createCriteria(clazz);
		criteria.add(Restrictions.eq(propertyName, value));
		return criteria.list();
	}
	
	protected Session getSession(){
		return hibernateTemplate.getSessionFactory().getCurrentSession();
	}
	
	public Object getObject(Class clazz,String propertyName,Object value){
		Session session = getSession();
		Criteria criteria = session.createCriteria(clazz);
		criteria.add(Restrictions.eq(propertyName, value));
		return criteria.uniqueResult();
	}
	
	public List getObjectsInTime(Class clazz,String propertyName,Date low, Date high){
		Session session = getSession();
		Criteria criteria = session.createCriteria(clazz);
		criteria.add(Restrictions.between(propertyName, DateUtil.convertDateToTimeStamp(low), DateUtil.convertDateToTimeStamp(high)));
		return criteria.list();
		
	}
	
	public List getObjects(Class clazz,Map<String, Object> map){
		Session session = getSession();
		Criteria criteria = session.createCriteria(clazz);
		for (String o : map.keySet()) {
			criteria.add(Restrictions.eq(o, map.get(o)));
		}
		return criteria.list();
	}
	
	public Object getObject(Class clazz,Map<String, Object> map){
		Session session = getSession();
		Criteria criteria = session.createCriteria(clazz);
		for (String o : map.keySet()) {
			criteria.add(Restrictions.eq(o, map.get(o)));
		}
		return criteria.uniqueResult();
	}
	
}
